import * as types from '../mutation-types'
import Vue from "vue";

const currentPrefix = 'currentUser_';
/**
 * 不同环境api不同
 */
const apiCross = function (key) {
  let domain = document.domain;
  if (domain === 'localhost') {
    return key + '-test';
  } else if (domain.indexOf('-test')) {
    return key + '-test';
  } else if (domain.indexOf('-pre')) {
    return key + '-pre';
  } else {
    return key;
  }
};

const api = {
  jy: 'http://' + apiCross('jy') + '.17daxue.cn/web-jy/app/',
  stat: 'http://' + apiCross('stat') + 'stat-test.17daxue.cn/web-stat/app/',
  img: 'http://img.17daxue.com/',
  passport: 'http://' + apiCross('passport') + '.17daxue.cn/web-passport/app/',
  el: 'http://' + apiCross('el') + '.17daxue.cn/web-elementary/api/',
};

const state = {
  api,
  currentUser: {
    get id() {
      return localStorage.getItem(currentPrefix + 'id');
    },
    get token() {
      return localStorage.getItem(currentPrefix + 'token');
    },
    get name() {
      return localStorage.getItem(currentPrefix + 'name');
    },
    get info() {
      return JSON.parse(localStorage.getItem(currentPrefix + 'info'));
    },
    get valid() {
      return new Date(localStorage.getItem(currentPrefix + 'valid'));
    }
  }
};

const mutations = {
  setCurrentUser(state, userdata) {
    for (let field in state.currentUser) {
      if (state.currentUser.hasOwnProperty(field)) {
        let key = 'currentUser_' + field;
        localStorage.setItem(key, userdata[field]);
      }
    }
    localStorage.setItem(currentPrefix + 'id', userdata['serverStudentId']);
    localStorage.setItem(currentPrefix + 'info', JSON.stringify(userdata));
    localStorage.setItem(currentPrefix + 'valid', new Date());
  },
  [types.app_logout](state) {
    localStorage.clear();
  }
};

const actions = {
  [types.app_login](context, {username, password, callback}) {
    Vue.axios.get(context.state.api.passport + 'user/login/doLogon?loginName=' + username + '&password=' + password)
      .then((response) => {
        let data = response.data;
        let userdata = data.userdata;
        if (userdata) {
          context.commit('setCurrentUser', userdata);
          callback(true, '登录成功');
        } else {
          callback(false, data.message);
        }
      }).catch((error) => {
      callback(false, error);
    });
  },
  [types.app_resume](context, callback) {
    let token = state.currentUser.sessionid;
    if (token) {
      Vue.axios.get(context.rootState.api.user.login + '?__cookie=true&__sid=' + token)
        .then((data) => {
          callback(true);
        }).catch((error) => {
        callback(false, '登录超时,请重新登录');
      });
    } else {
      callback(false);
    }
  },
  [types.app_logout](context, callback) {
    let token = state.currentUser.token;
    if (token) {
      localStorage.clear();
    }
  }
};

export default {
  state,
  mutations,
  actions
}
